package com.yft.data.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.yft.data.dao.PublicDao;
@Service
public class BlackListService {
	private static final Logger logger = Logger.getLogger(BlackListService.class);
	@Autowired
	private PublicDao publicDao;
	@Autowired
	private UserService userService;
	/**
	 * 获取黑名单
	 * @return
	 */
	@Cacheable("blacklist")
	public List<String> getBlackList() {
		String sql = "select phone from blacklist where userid is Null ";
		List<Map<String, Object>> blacklist = publicDao.getObjectList(sql);
		List<String> list = new ArrayList<String>();
		for (Map<String, Object> map : blacklist) {
			list.add((String) map.get("phone"));
		}
		//System.out.println("test");
		return list;
	}
	/**
	 * 获取用户定义的黑名单
	 * @param userid
	 * @return
	 */
	@Cacheable(value="userblacklist", key="#userid")
	public List<String> getBlackList(String userid) {
		String sql = "select phone from blacklist where userid = '"+userid+"'";
		List<Map<String, Object>> blacklist = publicDao.getObjectList(sql);
		List<String> list = new ArrayList<String>();
		for (Map<String, Object> map : blacklist) {
			list.add((String) map.get("phone"));
		}
		//System.out.println("test");
		return list;
	}
	
	/**
	 * 手工设置黑名单，记录下来是哪个用户设置的
	 * @param phone
	 * @param userid
	 * @return
	 */
	@CacheEvict(value="userblacklist", key="#userid")
	public int setBlock(String phone,String userid)
	{
		StringBuffer sb = new StringBuffer();
		sb.append("insert into blacklist (phone,userid) values ('");
		sb.append(phone+"','");
		sb.append(userid+"')");
		String sql = sb.toString();
		int i = publicDao.update(sql);
		return i;
	}
	
	/**
	 * 检查该企业的该用户id是否过期
	 * 为了使用spring的cache，放到了这里
	 * spring的cache，在同一个类中，不适用类名来调用，是不好用的，没法AOP进来
	 * @param corpid
	 * @param userid
	 * @return
	 */
	public boolean isNotExpire(int corpid,String userid)
	{
		//实现
		String nextpayStr = userService.getUserPayTime(corpid, userid);
		
		//从未付过费的情况下
		if(nextpayStr==null||nextpayStr.equals(""))
		{
			return false;
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		try {
			Date nextpaytime = dateFormat.parse(nextpayStr);

			Date now = new Date();
			if(nextpaytime.after(now))
			{
				return true;
			}
			else
			{
				return false;
			}
		} catch (ParseException e) {
			logger.debug("日期转换失败",e);
		} 
		return true;
	}
}
